import { Dep } from './dep.js'

export class Observer {
  
  constructor(data) {
    this.observer(data)
  }

  observer(data) {
    if (data && typeof data === 'object') {
      for (let key in data) {
        this.defineReactive(data, key, data[key])
      }
    }
  }

  defineReactive(obj, key, value) {
    //要考虑data中某个属性值为对象的情况，递归观察
    this.observer(value)
    const dep = new Dep()
    Object.defineProperty(obj, key, {
      get() {
        if (Dep.target) {
          dep.addSub(Dep.target)
        }
        return value
      },
      set: (newValue) => {
        if(newValue !== value) {
          //考虑新赋值的是对象
          this.observer(newValue)
          value = newValue
          dep.notify()
        }
      }
    })
  }
}